package com.nuoniu.sibanyun.interceptor.sql;

import com.nuoniu.sibanyun.annotation.DataAuth;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.dto.DynamicDto;
import com.nuoniu.sibanyun.userThread.DataScope;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Log4j2
@Component
@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public class QueryByAppInterceptor implements Interceptor {

    static int MAPPED_STATEMENT_INDEX = 0;// 这是对应上面的args的序号

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        UserInfo userInfo = UserThreadLocal.get();

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        //id为执行的mapper方法的全路径名，如com.uv.dao.UserMapper.insertUser
        String mId = ms.getId();
        //sql语句类型 select、delete、insert、update
        String sqlCommandType = ms.getSqlCommandType().toString();
        Object parameter = args[1];
        BoundSql boundSql  = ms.getBoundSql(parameter);

        //获取到原始sql语句
        String sql = boundSql.getSql();

        DataAuth dataAuth = getPermissionByDelegate(ms);
        if (null == dataAuth  || null == userInfo || userInfo.getUserName().equals("system")) {
            return invocation.proceed();
        }
        Object parameterObject = boundSql.getParameterObject();
        HashMap parameterMap = new HashMap();
        if(parameterObject instanceof MapperMethod.ParamMap){
            parameterMap = (MapperMethod.ParamMap)boundSql.getParameterObject();
        }else{

        }

        //组装新的sql
        //sql处理逻辑 + SQL替换
        String mSql = this.permissionSql(sql, parameterMap, dataAuth);
        // 重新new一个查询语句对像
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), mSql, boundSql.getParameterMappings(), boundSql.getParameterObject());

        // 把新的查询放到statement里
        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        final Object[] queryArgs = invocation.getArgs();
        queryArgs[MAPPED_STATEMENT_INDEX] = newMs;

        return invocation.proceed();
    }


    /**
     * 获取数据权限注解信息
     *
     * @param mappedStatement
     * @return
     */
    private DataAuth getPermissionByDelegate(MappedStatement mappedStatement) {
        DataAuth dataAuth = null;
        try {
            String id = mappedStatement.getId();
            String className = id.substring(0, id.lastIndexOf("."));
            String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
            final Class<?> cls = Class.forName(className);
            final Method[] method = cls.getMethods();
            for (Method me : method) {
                if (me.getName().equals(methodName) && me.isAnnotationPresent(DataAuth.class)) {
                    dataAuth = me.getAnnotation(DataAuth.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataAuth;
    }

    /**
     * 数据权限sql包装
     * @param sql
     * @return
     */
    private String permissionSql(String sql,HashMap parameterObject,DataAuth dataAuth){
        String tableAlias = dataAuth.tableAlias();
        String companyField = dataAuth.companyField();
        String officeField = dataAuth.officeField();
        String personalField = dataAuth.personalField();
        UserInfo userInfo = UserThreadLocal.get();
        DataScope dataScope = userInfo.getDataScope();
        if( !sql.contains("WHERE")){
            String randomStr = com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(3);
            String randomNum = com.nuoniu.sibanyun.common.lang.StringUtils.getRandomNum(5);
            String errCode = randomStr + randomNum;
            log.error("数据权限SQL拦截器错误({})，必须带where关键字",errCode);
            throw new NuoNiuException("系统错误("+ errCode +")：请联系管理员");
        }
        //1.根据where关键字切分SQL
        String fromSql = StringUtils.substringBeforeLast(sql, "WHERE");
        String afterLast = StringUtils.substringAfterLast(sql, "WHERE");
        String addSql = "";
        addSql +=  tableAlias + "." + companyField + " = " + dataScope.getCompanyId();
        if(!(null != dataScope.getType() && dataScope.getType() == 3)){
            if(StringUtils.isNotBlank(dataScope.getOfficeIds()) || StringUtils.isNotBlank(dataScope.getUserIds())){
                addSql += " AND ( ";
                boolean isHaveOfficeIds = false;
                //非个人权限 type=1  是个人权限
                /** 数据跟到 用户走 ，不在使用记录里面的部门信息 进行查询，一切按人来查询 */

                if(StringUtils.isNotBlank(dataScope.getUserIds())){
                    String or = " OR ";
                    if(!isHaveOfficeIds) {
                        or="";
                    }
                    addSql += or + tableAlias + "." + personalField + " IN( " + dataScope.getUserIds() + ")";
                    isHaveOfficeIds = true;
                }
                if("crm".equals(tableAlias)){
                    //1.共享给我的客户
                    String shareOr = " OR ";
                    if(!isHaveOfficeIds) {
                        shareOr="";
                    }
                    addSql += shareOr + " (crm.share_type = 1 AND FIND_IN_SET(" + userInfo.getUserId() + ",crm.share_user_id) AND ( crm.share_end = 1 OR crm.share_time > NOW()) )";
                    //2.公司所有的 线索客户

                    //2.如果是客户管理
                    boolean dynamicDto1 = parameterObject.containsKey("dynamicDto");
                    if(dynamicDto1){
                        Object dynamicDto = parameterObject.get("dynamicDto");
                        DynamicDto dto = (DynamicDto)dynamicDto;
                        Boolean isGetSaleManId = dto.getIsGetSaleManId(); // 是否 关联业务员
                        String crmType = dto.getCrmType();
                        //如果还包含 公共客户
                        if(null != crmType && crmType.contains("0")){
                            String crmOr = " OR ";
                            if(!isHaveOfficeIds) {
                                crmOr="";
                            }
                            String crmSql = "crm.crm_type = 0 AND crm.company_id = " + userInfo.getCompanyId();
                            if(isGetSaleManId){
                                crmSql += " AND touch.sales_man_id IN( " + dataScope.getUserIds() + ")";
                            }
                            addSql += crmOr + " ("+ crmSql +" ) ";
                        }
                    }else{
                        String crmOr = " OR ";
                        if(!isHaveOfficeIds) {
                            crmOr="";
                        }
                        addSql += crmOr + " (crm.crm_type = 0 AND crm.company_id = " + userInfo.getCompanyId()+" ) ";
                    }
                }
                addSql += " ) ";
            }

        }

        String resultSql = fromSql + " WHERE " +  addSql;
        if(StringUtils.isNotBlank(afterLast)){
            resultSql += " AND " + afterLast;
        }
        return resultSql;
    }

    public static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;
        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
